package com.xiaoha.pogy.file;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Component
public class FileService {

    private Path fileStorageLocation;

    public FileService(@Value("D:/aplus") String path){
        this.fileStorageLocation = Paths.get(path).toAbsolutePath().normalize();
        try {
            Files.createDirectories(this.fileStorageLocation);
        } catch (IOException e){
            throw new FileException("Could not create the directory",e);
        }
    }

    public String storeFile(MultipartFile file){
        String file_name = StringUtils.cleanPath(file.getOriginalFilename());

        try {
            if (file_name.contains("..")){
                throw new FileException("Sorry! Filename contains invalid path sequence " + file_name);

            }
            Path targetLocation = this.fileStorageLocation.resolve(file_name);
            Files.copy(file.getInputStream(),targetLocation, StandardCopyOption.REPLACE_EXISTING);
            return file_name;
        } catch (IOException ex) {
            throw new FileException("Could not store file " + file_name + ". Please try again!",ex);
        }
    }

    public Resource loadFileAsResource(String file_name){
        try{
            Path filePath = this.fileStorageLocation.resolve(file_name).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists()){
                return resource;
            }else{
                throw new FileException("File not found " + file_name);
            }
        }catch (MalformedURLException ex){
            throw new FileException("File not found " + file_name,ex);
        }
    }

}
